"""
https://docs.python.org/3/library/queue.html


Queue.task_done()
Indicate that a formerly enqueued task is complete. Used by queue consumer threads. For each get() used to fetch a task,
 a subsequent call to task_done() tells the queue that the processing on the task is complete.

If a join() is currently blocking, it will resume when all items have been processed (meaning that a task_done() call
was received for every item that had been put() into the queue).

Raises a ValueError if called more times than there were items placed in the queue.


Queue.join()
Blocks until all items in the queue have been gotten and processed.

The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer
thread calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of
unfinished tasks drops to zero, join() unblocks.



https://stackoverflow.com/questions/49637086/python-what-is-queue-task-done-used-for

Queue.task_done lets workers say when a task is done. Someone waiting for all the work to be done with Queue.join will
wait until enough task_done calls have been made, not when the queue is empty.

"""

from queue import Queue
from threading import Thread


class ClosableQueue(Queue):
    SENTINAL = object()

    def close(self):
        self.put(self.SENTINAL)

    def __iter__(self):
        while True:
            item = self.get()
            try:
                if item is self.SENTINAL:
                    print('Return at SENTINAL')
                    return
                print(f'Yiled {item}')
                yield item
            finally:
                print('Task done is invoked (finally)')
                self.task_done()
                # self.task_done()  # ValueError: task_done() called too many times


if '__main__' == __name__:

    cq = ClosableQueue()
    for i in range(5):
        cq.put(i)
    cq.close()

    for i, row in enumerate(cq):
        pass

    cq.join()

    print('Over')
